<template>
  <view class="retail-list over-css">
    <uni-row v-if="config.listLayout == 'batchList' && configLoaded" class="retail-list">
      <!-- 左右两侧布局列表  右边列表 -->

      <view class="retail-list-left padding-0" v-if="inPageType == 'batch-update'">
        <view class="retail-list-left-top" v-if="gridButton.length > 0">

          <slot name="rFilter"></slot>

          <view class="button-group">

            <button @click="onGridButton(item)" class="cu-btn g-button  margin-tb-sm lg"
              v-for="(item,index) in gridButton" :key="index">
              <text class="cuIcon-roundaddfill add-icon" v-if="item.button_type == 'add'"></text>{{item.button_name}}
            </button>
            <button v-if="showBatchSubmitRun" @click="onGridButton('batch-submit')"
              class="cu-btn g-button margin-tb-sm lg">提交所有</button>
          </view>

        </view>

        <view class="retail-list-left-middle shadow-warp full-height bg-white" style="overflow-y: initial;">

          <rFilter ref="filterTabs" :inListType="config.listLayout" :labelPos="'top'"
            v-if="tabs.length > 0 && gridHeader.length > 0" :tabs="tabs" :srv="config.serviceName" :cols="gridHeader"
            @on-input-value="onFilterChange" @on-change="getTableDatas"></rFilter>
        </view>
        <view class="retail-list-left-bottom bg-white" v-if="gridButton.length > 0">
          <slot name="leftBottom"></slot>
        </view>
      </view>
      <view :class="inPageType !== 'batch-update' ? 'retail-list-right' : 'retail-list-right retail-list-right-full'">
        <view class="retail-list-right-top bg-white padding" v-if="inPageType !== 'batch-update'">
          <bSelect ref="bSelect" :mainService="config.serviceName" v-if="editorType == 'add'"
            :servie="'srvretail_goods_classify_select'" :isTree="true" @on-select-change="onBatchSelect"
            :initSelectedData="listData"></bSelect>
          <view class="flex align-center justify-around full-width" v-if="editorType != 'add'">
            <view class="text-lg margin-right" v-if="config.title">单号：{{config.title}}</view>
            <view class="text-lg margin-right" v-if="config.state">状态：{{config.state}}</view>
            <view class="text-lg margin-right" v-if="config.operator_name">操作人：{{config.operator_name}}</view>
            <view class="text-lg" v-if="config.create_time">创建时间：{{config.create_time}}</view>
            <view class="text-lg" v-if="config.submit_time">提交时间：{{config.submit_time}}</view>
          </view>
          <slot name="rightTop"></slot>
        </view>
        <view class="retail-list-right-middle">
          <slot name="rLayoutRight">

          </slot>
          <view class="loading-box" style="" v-if="loading==true">
            <u-loading-icon text="加载中" size="48" textSize="24"></u-loading-icon>
          </view>
          <uni-table class="show-y-scroll-bar" :type="selection===true?'selection':''" border stripe emptyText="暂无更多数据"
            :stripe="false" :loading="loading">
            <!-- 表头行 -->
            <uni-tr class="fixed-head">
              <uni-th width="200" align="center" v-for="(headCol,index) in gridHeader" v-if="headCol.in_list == 1"
                :key="index">{{headCol.label}}
              </uni-th>
              <uni-th align="center" width="200" v-if="editorType==='add'">
                操作
              </uni-th>
            </uni-tr>
            <!-- 表格数据行 -->
            <uni-tr v-for="(dataRow,index) in listData" :key="dataRow.goods_no" v-if="config.listLayout == 'batchList'">
              <uni-td v-for="(headCol,i) in listColumns" :key="headCol.columns"
                style="min-width: 20rem;text-align: center;">
                <!-- <uni-td v-for="(headCol,i) in gridHeader" :key="i" v-show="headCol.in_list == 1"> -->
                <view class="" style="text-align: center;" @click.stop="onItemClick(dataRow)">
                  <text v-if="headCol.columns==='goods_barcode'">
                    {{setTableValue(headCol,dataRow)}}
                    <!-- {{dataRow[headCol.columns]|| "-"}} -->
                  </text>
                  <view class="" v-else-if="config.serviceName==='srvretail_stock_warning_select'">
                    <uni-easyinput :focus="index===0&&headCol.columns==='warehousing_num'"
                      @input="keyUserInValue($event,dataRow,headCol.columns)" primaryColor="#38C09E" type="digit"
                      v-model="dataRow[headCol.columns]" @change="numberChange($event,dataRow,headCol.columns)"
                      v-if="config.serviceName==='srvretail_stock_warning_select'&&( ['max_stock','min_stock'].includes(headCol.columns))" />
                    <text v-else>
                      {{setTableValue(headCol,dataRow)}}
                    </text>
                  </view>
                  <view
                    v-else-if="['srvretail_warehousing_add','srvretail_warehousing_update'].includes(config.serviceName)&&( ['warehousing_num','purchase_price'].includes(headCol.columns))">
                    <uni-easyinput :focus="index===0" @input="keyUserInValue($event,dataRow,headCol.columns)"
                      primaryColor="#38C09E" type="number" v-model="dataRow[headCol.columns]"
                      @change="numberChange($event,dataRow,headCol.columns)"
                      v-if="headCol.columns==='warehousing_num'" />
                    <uni-easyinput @input="keyUserInValue($event,dataRow,headCol.columns)" primaryColor="#38C09E"
                      type="digit" v-model="dataRow[headCol.columns]"
                      @change="numberChange($event,dataRow,headCol.columns)" v-else />
                  </view>
                  <view
                    v-else-if="['srvretail_issue_add','srvretail_issue_update'].includes(config.serviceName)&&( ['issue_num','shipment_price'].includes(headCol.columns))">
                    <uni-easyinput :focus="index===0&&headCol.columns==='issue_num'"
                      @input="keyUserInValue($event,dataRow,headCol.columns)" primaryColor="#38C09E" type="digit"
                      @change="numberChange($event,dataRow,headCol.columns)" v-model="dataRow[headCol.columns]" />
                  </view>
                  <view
                    v-else-if="['srvretail_inventory_update','srvretail_inventory_add'].includes(config.serviceName)&&( ['inventory_num'].includes(headCol.columns))">
                    <uni-easyinput :focus="index===0&&headCol.columns==='inventory_num'"
                      @change="numberChange($event,dataRow,headCol.columns)"
                      @input="keyUserInValue($event,dataRow,headCol.columns)" primaryColor="#38C09E" type="number"
                      v-model="dataRow[headCol.columns]" />
                  </view>
                  <view
                    v-else-if="['srvretail_loss_reporting_update','srvretail_loss_reporting_add'].includes(config.serviceName)&&( ['loss_reason','loss_num'].includes(headCol.columns))">
                    <uni-data-select v-if="headCol.col_type == 'Enum'" v-model="dataRow[headCol.columns]"
                      :localdata="headCol._options||[]"></uni-data-select>
                    <uni-easyinput :focus="index===0&&headCol.columns==='loss_num'"
                      @change="numberChange($event,dataRow,headCol.columns)"
                      @input="keyUserInValue($event,dataRow,headCol.columns)" primaryColor="#38C09E" type="digit"
                      v-model="dataRow[headCol.columns]" v-else />
                  </view>
                  <gStrIntercept :defaultStr="setTableValue(headCol,dataRow)" :len="20" v-else>
                  </gStrIntercept>
                </view>
              </uni-td>
              <uni-td v-if="editorType==='add'" align="center">
                <button class="button bg-red sm" @click="deleteItem(dataRow)">删除</button>
              </uni-td>
            </uni-tr>
          </uni-table>
          <rpaging class="r-paging" v-if="config&&config.defaultData !== 'batch-select'" :inpage="listpage"
            @on-page-change="onpagintion"></rpaging>
        </view>
        <view class="retail-list-right-bottom  bg-white padding" v-if="submitOnConfirm!==true">
          <view class="buttom-layout" v-if="configLoaded">
            <view class="count-layout padding" v-if="inPageType !== 'batch-update'">
              <view class="padding-sm">{{listDataSum(config.popupColumns[0],listData)}}</view>

              <view class="padding">数量统计</view>
            </view>
            <view class="count-layout padding"
              v-if="inPageType !== 'batch-update'&&!['srvretail_inventory_add111','srvretail_inventory_select222','srvretail_inventory_update333'].includes(config.serviceName)">
              <view class="padding-sm">
                {{listDataSum(config.popupColumns[config.popupColumns.length - 1],listData)}}
              </view>
              <view class="padding">金额统计</view>
            </view>
          </view>
          <view class="buttom-buttons" v-if="configLoaded && editorType !== 'detail'">
            <button  clsss="g-button" @click="submitInStock('delete-all')" type="info"
              v-if="editorType == 'add'">清空列表</button>
            <button  clsss="g-button bg-red" @click="submitInStock('delete-current')"
              v-if="editorType == 'update'">删除</button>
            <button :disabled="false" clsss="g-button" type="info" @click="onSelect('inventory-type')"
              v-if="editorType == 'add' && config.serviceName.indexOf('srvretail_inventory_') !== -1">{{activeInventoryType }}</button>
            <button  type="primary" clsss=" g-button" @click="submitInStock('save')"
              v-if="editorType == 'add'||editorType==='update'">保存</button>
            <button  type="primary" clsss=" g-button" @click="submitInStock('submit')"
              v-if="editorType !== 'detail'">提交</button>
          </view>
        </view>
        <view class="retail-list-right-bottom bg-white padding text-right justify-end"
          v-else-if="config.serviceName==='srvretail_stock_warning_select'">
          <view class="">
          </view>
          <button class="g-button" @click="$emit('save',listData)" v-if="editorType !== 'detail'">保存</button>
        </view>
      </view>
    </uni-row>
    <uni-popup ref="popupUpdate" type="center" :mask-click="false">
      <uni-card style="overflow: inherit;">
        <template v-slot:title>
          <view class="flex solid-bottom padding-lg justify-between text-lg">
            <view class="text-lg">{{checkedItem.goods_name}}</view>
            <text class="cuIcon-close" @click="close"></text>
          </view>
        </template>
        <view class="uni-body uni-mt-5">
          <view class="item-update flex padding justify-between">
            <view class="item-update-left padding" style="width:25vw">
              <uni-forms :modelValue="formData" :label-width="'20rem'">
                <uni-forms-item v-show="fieldInUpdateColumns(field.columns)" :label="field.label" :name="field.columns"
                  v-for="(field,l) in updateColumns" :required="field.isRequire===true?true:false" :key="l">
                  <view class="uni-input" :class="{'active':formItemActive===field.columns}"
                    @click="changeFormItem(field.column)"
                    :disabled="['subtotal_amount','cost_price','profit_loss_amount','goods_stock','profit_loss_num','inventory_type','inventory_type','purchase_amount','cost_amount'].includes(field.column)"
                    v-if="(field.type == 'number' ||  field.type == 'digit')" v-model="formData[field.column]"
                    type="digit">
                    {{formData[field.column]||'0'}}
                  </view>
                  <uni-data-select v-if="field.col_type == 'Enum'" v-model="formData[field.column]"
                    :localdata="field._options"></uni-data-select>
                </uni-forms-item>
              </uni-forms>
            </view>
            <view class="item-update-right" style="width:25vw">
              <gKeyboard :defaultValue="formData[formItemActive]" @on-value-change="keyUserInValue">
              </gKeyboard>
            </view>
          </view>
        </view>
        <view slot="actions" class="card-actions button-group padding-lg border-top">
          <button class="card-actions-item cu-btn g-button margin-right" type="error" @click="actionsClick('delete')"
            v-if="inPageType !== 'batch-update'">
            <text class="cuIcon-delete" color="#999"></text>
            <text class="card-actions-item-text">删除</text>
          </button>
          <button class="card-actions-item cu-btn g-button margin-right " type="info" @click="close">
            <text class="card-actions-item-text">取消</text>
          </button>
          <button class="card-actions-item cu-btn g-button " @click="actionsClick('submit')">
            <text class="card-actions-item-text">确认</text>
          </button>
        </view>
      </uni-card>
    </uni-popup>
    <view>
      <!-- 操作确认 -->
      <uni-popup ref="alertDialog" type="dialog">
        <uni-popup-dialog :type="'info'" cancelText="取消" confirmText="确定" :title="dialogTitle||'确认操作!'" content=""
          @confirm="dialogConfirm(true)" @close="dialogClose"></uni-popup-dialog>
      </uni-popup>

      <!-- 选择盘点类型 -->
      <uni-popup ref="selectType" type="dialog">
        <uni-popup-dialog :type="'info'" cancelText="取消" confirmText="同意" title="盘点类型" content=""
          @confirm="selectConfirm(true)">
          <view class="uni-px-5">
            <!-- <view class="text">单选选中：{{JSON.stringify(radio2)}}</view> -->
            <uni-data-checkbox mode="button" v-model="activeInventoryType" :localdata="inventoryType">
            </uni-data-checkbox>
          </view>

        </uni-popup-dialog>
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import rFilter from '@/components/retail-list/retail-filter.vue'
  import rpaging from '@/components/bx-pagination/bx-pagination.vue'
  import bSelect from '@/components/g-batch-select/g-batch-select.vue'
  import gKeyboard from '@/components/g-batch-update/g-num-keyboard.vue'
  import gStrIntercept from '@/components/g-batch-update/strIntercept.vue'
  export default {
    name: "g-batch-update",
    components: {
      rFilter,
      rpaging,
      bSelect,
      gKeyboard,
      gStrIntercept
    },
    data() {
      return {
        dialogTitle: "",
        mainV2: null, // 主表service v2
        inventoryType: [{
          text: "覆盖",
          value: "覆盖"
        }, {
          text: "累加",
          value: "累加"
        }],
        activeInventoryType: "覆盖",
        mainV2Loaded: false,
        childAddFieldsModel: null, // 子表新增v2
        childAddFieldsModelLoaded: false, // 子表 新增 v2
        serviceV2: {},
        configLoaded: false,
        listDataLoaded: false,
        listData: [],
        searchVal: "",
        tabsBuild: false,
        tabs: [],
        filterCondition: [],
        relation_Conditions: {},
        checkedItem: null,
        checkedItemUpdateModel: [],
        updateColumns: [],
        detailLoaded: false, // 详情部分是否加载
        defaultData: null,
        listpage: {
          pageNo: 1,
          rownumber: 10
        },
        more: 'noMore', // more/loading/noMore
        triggered: false,
        relationCondition: null, // 过滤条件
        tabsType: "request", //request  custom
        faceListDataFields: [],
        loading: false,
        // popupColumns: ["issue_num", "shipment_price", "shipment_amount"],
        popupColumns: ["warehousing_num", "sale_price", "subtotal_amount"],
        formData: {
          // "warehousing_num":"",
          // "sale_price":"",
          // "subtotal_amount":""
        },
        formItemActive: "",
        submitAlertDialog: "", // 点击
        form: {

        }
      };
    },
    props: {
      // 编辑弹窗中点击确认直接提交数据
      submitOnConfirm: {
        type: Boolean,
        default: false
      },
      editorType: {
        type: String,
        default: function() {
          return "add"
        }
      },
      config: {
        type: Object,
        default: function() {
          return {
            serviceName: "srvretail_member_info_select",
            listLayout: "listAndDetail", // listAndDetail listAndFilter  list
            detailPath: "simple", //  simple  基础的； 或者配置页面路由 路由格式待定
            popupColumns: ["warehousing_num", "sale_price", "subtotal_amount"],
            page: {
              pageNo: 1,
              rownumber: 20
            },
          }
        }
      },
      inPageType: {
        type: String,
        default: function() {
          return "list"
        }
      },
      columnRowConfig: {
        type: [Array],
        default: function() {
          return []
        }
      },
      heightTop: {
        type: String,
        default: function() {
          return "60px"
        }
      },
      searchValKey: {
        type: String,
        default: function() {
          return ""
        }
      },
      condition: {
        type: Array,
        default: function() {
          return []
        }
      },
      custGridHeader: {
        type: Array,
        default: function() {
          return []
        }
      },
      selection: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      listColumns() {
        if (Array.isArray(this.gridHeader) && this.gridHeader.length > 0) {
          return this.gridHeader.filter(item => item.in_list === 1)
        }
        return []
      },
      childServiceBuild: function() {
        let srv = false
        let main = this.mainV2
        if (main && main.hasOwnProperty('child_service')) {
          let childList = main.child_service
          if (childList.length > 0) {
            for (let child of childList) {
              let foreignKey = child.foreign_key
              if (foreignKey.referenced_table_name == main.main_table) {
                srv = this.deepClone(child)
              }
            }
          }
        }
        return srv
      },
      custTabsRun: function() {
        let cfg = this.config.custTabs || []
        return cfg
      },
      moreRun: function() {
        let more = this.more
        let page = this.listpage
        page.pageNo * page.rownumber < page.total ? more == 'more' : 'noMore'
        return more
      },
      gridHeader: function() {
        let self = this
        let cols = this.serviceV2?._fieldInfo || []
        if (this.inPageType == 'batch-update') {
          cols = this.mainV2?._fieldInfo || []
        }
        let addColsModel = this.childAddFieldsModel ? this.childAddFieldsModel._fieldInfo : []
        let confHeader = this.custGridHeader
        let res = []
        if (this.editorType === 'add') {
          cols = cols.filter((item) => item && item.in_add !== 0)
        } else {
          cols = cols.filter((item) => item && item.in_list !== 0)
        }
        if (confHeader && confHeader.length > 0) {
          for (let col of confHeader) {
            for (let v2col of cols) {
              let colModel = self.deepClone(v2col)
              for (let aCol of addColsModel) {
                if (col == aCol.columns && aCol.redundant) {
                  colModel['redundant'] = self.deepClone(aCol.redundant)
                  // console.log("colModel['redundant'] confHeader",colModel,aCol.redundant)
                }
                colModel['init_expr'] = aCol.init_expr
              }
              if (col == v2col.columns) {
                res.push(colModel)
              }
            }
          }

        } else {
          for (let v2col of cols) {
            let colModel = this.deepClone(v2col)
            for (let aCol of addColsModel) {
              if (v2col.columns == aCol.columns) {
                if (aCol.redundant && aCol.redundant) {
                  colModel['redundant'] = self.deepClone(aCol.redundant)
                }
                // console.log("init_expr",aCol.init_expr, self.deepClone(aCol.redundant))
                colModel['init_expr'] = aCol.init_expr
                // console.log("colModel['redundant'] confHeader",colModel,aCol.redundant)
                switch (colModel.col_type) {
                  case "Enum":
                    colModel['_options'] = v2col.options.map((item) => {
                      let tag = {
                        text: item.label,
                        value: item.value,
                      }
                      return tag
                    })
                    break;
                  default:
                    break;
                }
              }
            }
            res.push(colModel)
          }
          // res = cols
        }

        return res || []
      },
      conditionRun: function() {
        let cond = this.condition.concat(this.filterCondition)
        return cond
      },
      gridButton: function() {
        let buts = this.serviceV2.gridButton || []
        buts = buts.filter((item) => item.button_type == 'add')
        return buts || []
      },
      cols: function() {
        let buts = this.serviceV2.srv_cols || []
        buts = buts.filter((item) => item.in_list == 1)
        return buts || []
      },
      moreConfig: function() {
        let cfg = this.serviceV2.more_config || {}
        let textStyle = {
          fontSize: 20,
          fontWeight: "bold",
          textAlign: "left",
        }
        let showConfig = {
          textStyle: textStyle,
          suffix: "",
          prefix: ""
        }
        let aioPage = {
          listType: "listAndDetail",
          listItem: [{
            colName: "member_name",
            colSpan: 1,
            colValType: "string", // string number 
            showConfig: showConfig

          }, {
            colName: "menber_no",
            colSpan: 0.5,
            colValType: "string", // string number 
            showConfig: showConfig
          }, {
            colName: "member_phone",
            colSpan: 0.5,
            colValType: "string", // string number 
            showConfig: showConfig
          }]
        }
        let listCfg = cfg.hasOwnProperty("aioPage") ? cfg.aioPage : aioPage
        return listCfg
      },
      relationConditionRun: function() {
        let relationCondition = {}
        let filterRelation = this.relationCondition
        let headerinputSearch = this.relation_Conditions
        if (filterRelation && filterRelation.data && filterRelation.data.length > 0) {
          relationCondition['data'] = filterRelation['data']
          relationCondition['relation'] = "AND"
          if (headerinputSearch && headerinputSearch.data && headerinputSearch.data.length > 0) {
            relationCondition['data'] = filterRelation['data'].concat(headerS.data)
          }
        }


        return relationCondition
      }
    },
    created() {
      this.getPageConfig()
      // console.log("列表加载了--", this.config, this)
      if (this.inPageType == 'list') {

      } else if (this.inPageType == 'batch-update') {

      }
    },

    methods: {
      deleteItem(e, index) {
        uni.showModal({
          title: '提示',
          content: '确认删除?',
          success: (res) => {
            if (res.confirm) {
              this.listData = this.listData.filter(item => item.goods_barcode !== e.goods_barcode)
            }
          }
        })
      },
      setTableValue(col, row) {
        let res = (row[col.columns] == 0 ? '0' : row[col.columns]) || ''
        if (!res && col?.col_type === 'Money') {
          res = '0'
        }
        return res || '-'
      },
      batchUpdateDataRun() {
        let reqs = []
        let updateCols = this.config.popupColumns
        if (this.inPageType == 'batch-update' && this.config.serviceName == 'srvretail_stock_warning_select') {
          this.listData.forEach((item) => {
            let oldData = item['_oldData']
            let isUpdateed = false
            let req = {
              "serviceName": "srvretail_stock_warning_update",
              "data": [{}],
              "condition": [{
                "colName": "id",
                "value": 60,
                "ruleType": "eq"
              }]
            }
            for (let col of updateCols) {
              if (item[col] !== oldData[col]) {
                req.data[0][col] = item[col]
                req.condition[0].value = item.id
                isUpdateed = true
              }
            }
            if (isUpdateed) {
              reqs.push(req)
            }
          })
        }

        return reqs
      },
      onSelect() {
        this.$refs.selectType.open()
      },
      fieldInUpdateColumns(col) {
        let cols = []
        cols = this.config.popupColumns.filter((item) => item == col)
        return cols.length > 0
      },
      changeFormItem(col) {
        this.formItemActive = col
      },
      buildFormDataColumn(cols) {
        for (let col of cols) {
          this.$set(this.formData, col, '0')
          // this.formData[col] = 0
        }
        // console.log('buildFormDataColumn',this.deepClone(this.formData))
        this.formItemActive = this.config.popupColumns[0]
      },
      getPageConfig() {
        let self = this
        let pageType = this.inPageType == 'detail' ? 'detaillist' : 'list'
        this.page = this.config.page
        this.loading = true
        this.tabsType = this.config.tabsType || 'request'
        let type = 'addchildlist'
        switch (this.editorType) {
          case 'add':
            type = 'addchildlist'
            break;
          case 'update':
            type = 'updatechildlist'
            break;
          case 'detail':
            type = 'detaillist'
            break;
          default:
            break;
        }
        if (this.config.popupColumns) {
          // 装载弹窗修改字段
          this.buildFormDataColumn(this.config.popupColumns)
        }
        if (this.configLoaded && this.mainV2Loaded) {
          this.getListData()
        } else {
          let pageType = 'detail'
          if (this.inPageType == 'batch-update') {
            pageType = 'list' // 批量编辑
          } else if (this.editorType === 'update') {
            // pageType = 'update'
          }
          let useType = this.editorType == 'add' ? 'select' : this.editorType
          if (this.editorType) {
            this.getServiceV2(this.config.serviceName, 'select', pageType).then((res) => {
              this.mainV2 = res
              this.mainV2Loaded = true
              this.config
              if (this.config.defaultData !== 'batch-select') {
                if (this.inPageType == 'batch-update') {
                  // 批量修改 加载默认数据 获取v2
                  let updateSrv = this.config.serviceName.replace("select", this.editorType)
                  this.getServiceV2(updateSrv, 'update', this.editorType).then((
                    res) => {
                    this.serviceV2 = res
                    this.configLoaded = true
                    self.$set(self, 'childAddFieldsModel', res)
                    // self.childAddFieldsModel = res
                    self.childAddFieldsModelLoaded = true

                    this.childBuildAddFields()
                    if (this.tabsType == 'custom' && this.config.custTabs) {
                      this.buildSections(this.config.custTabs, 'custom')
                    }
                    this.getListData(1, type)
                  })
                  // this.getListData(1, type)
                } else {
                  this.getDefaultData()
                }
              } else {
                if (this.childServiceBuild) {
                  this.getServiceV2(this.childServiceBuild.service_name, 'select', type).then((
                    res) => {
                    this.serviceV2 = res
                    this.configLoaded = true
                    this.childBuildAddFields()
                    this.getListData(1, type)
                  })
                }
              }
            })
          } else if (this.childServiceBuild) {
            // let childsrv = this.childServiceBuild ? this.childServiceBuild.service_name : this.config.childService
            this.getServiceV2(this.childServiceBuild.service_name, 'select', type).then((res) => {
              this.serviceV2 = res
              this.configLoaded = true
              // if(this.serviceV2.tabs && this.tabsType == 'request'){
              // 	this.buildSections(this.serviceV2.tabs)
              // }else if(this.tabsType == 'custom' && this.config.custTabs){
              // 	this.buildSections(this.config.custTabs,'custom')
              // }
              this.getListData(1, type)
            })
          }

        }

      },
      childBuildAddFields() {
        let self = this
        let childAddFieldsModel = null
        let childSrv = self.serviceV2.service_name.replace("select", this.editorType)
        if (!self.childAddFieldsModelLoaded) {
          self.getServiceV2(childSrv, this.editorType, this.editorType).then((res) => {
            self.$set(self, 'childAddFieldsModel', res)
            self.childAddFieldsModelLoaded = true
          })
        }
      },
      getDefaultData() {
        let self = this
        this.loading = true
        let srv = this.mainV2.service_name
        let cond = this.conditionRun
        let req = this.selectRequestObjs(srv, cond, null, self.relationConditionRun)
        // delete this.listpage.total
        req["page"] = {
          pageNo: 1,
          rownumber: 10
        }
        if (self.mainV2Loaded && this.config.listLayout == 'batchList' && this.config.defaultData !==
          "batch-select") {
          self.$fetch('select', srv, req).then((res) => {
            if (res.success) {
              self.defaultData = res.data
              self.getListData()
            }
          })
        }
      },
      getListData(pageNo, type) {
        let self = this
        let srv = this.serviceV2.select_service_name ? this.serviceV2.select_service_name : this.serviceV2
          .service_name
        let cond = this.conditionRun

        if (this.editorType !== 'add' && this.inPageType != 'batch-update' && Array.isArray(self.defaultData) && self
          .defaultData.length > 0) {
          cond = [{
            colName: self.config.childKeyCol,
            ruleType: "eq",
            value: self.defaultData[0][self.config.childKeyCol]
          }]
        }
        let listType = type || 'swipe'
        let req = this.selectRequestObjs(srv, cond, null, this.relationConditionRun)
        req["page"] = this.listpage ? this.listpage : {
          pageNo: 1,
          rownumber: 10
        }
        if (pageNo) {
          req.page.pageNo = pageNo
        }
        if (self.serviceV2 && this.configLoaded) {
          if (this.configLoaded && this.config.listLayout == 'batchList' && this.config.defaultData !==
            "batch-select") {
            this.loading = true
            this.$fetch('select', srv, req).then((res) => {
              this.loading = false
              if (res.success) {
                if (pageNo !== 1 && pageNo !== null && pageNo !== undefined && listType ==
                  'swipe') {
                  this.listData = this.listData.concat(res.data)
                } else {
                  this.listData = []
                  this.listData = res.data
                }
                if (this.inPageType == 'batch-update') {
                  this.listData = this.listData.map((item) => {
                    item['_oldData'] = self.deepClone(item)
                    return item
                  })
                }
                self.$set(self.listpage, 'pageNo', res.page.pageNo)
                self.$set(self.listpage, 'rownumber', res.page.rownumber)
                self.$set(self.listpage, 'total', res.page.total)
                if (res.page.pageNo * res.page.rownumber < res.page.total) {
                  self.more = "more"
                } else {
                  self.more = "noMore"
                }
                this.loading = false
                self.triggered = false
                this.$emit('list-load', this.listData)
              }
            })
          }
        } else if (this.childServiceBuild) {
          this.getServiceV2(this.childServiceBuild.service_name, 'select', 'updatechildlist').then((res) => {
            this.serviceV2 = res
            this.configLoaded = true
            // if(this.serviceV2.tabs && this.tabsType == 'request'){
            // 	this.buildSections(this.serviceV2.tabs)
            // }else if(this.tabsType == 'custom' && this.config.custTabs){
            // 	this.buildSections(this.config.custTabs,'custom')
            // }
            this.childBuildAddFields()
            this.getListData()
          })
        }
        this.loading = false

      },
      onGridButton(e) {
        // let url = `/pages/public/form/form?serviceName=${e.service_name}&type=add`
        // if(e.button_type == 'add'){

        // 	switch (e.service_name){
        // 		case "srvretail_warehousing_add":
        // 			url = `/pages/main/stockmgt/stock-batch-submit?serviceName=${e.service_name}&type=add`
        // 			break;
        // 		default:


        // 			break;
        // 	}
        // 	uni.navigateTo({
        // 	  url
        // 	})
        // }else{

        // }
      },

      onItemClick(e) {
        console.log(e);
        // if (['srvretail_warehousing_add', 'srvretail_issue_add'].includes(this.config.serviceName)) {
        return
        // }
        let self = this
        this.detailLoaded = false
        let updateData = this.deepClone(e)
        let heads = this.gridHeader
        this.$set(this, 'checkedItem', updateData)
        if (this.editorType == 'add' || (this.editorType == 'update' && this.config.serviceName ==
            'srvretail_stock_warning_select')) {
          for (let head of heads) {
            for (let cfgcol of self.config.popupColumns) {
              if (cfgcol == head.column && cfgcol == 'inventory_type') {
                if (head.init_expr && (head.init_expr == "mainData.inventory_type")) {
                  updateData[cfgcol] = self.activeInventoryType
                }
              }
              self.$set(self.formData, cfgcol, updateData[cfgcol])
            }
            for (let col in updateData) {
              self.$set(self.formData, col, updateData[col])
            }
          }

          // for (let col of self.config.popupColumns) {
          // 	self.$set(self.formData, col, updateData[col])
          // }
          // this.checkedItem = e
          this.$nextTick(() => {
            // this.$emit("on-list-item-checked",e)
            this.$refs.popupUpdate.open()
            this.detailLoaded = true
          })
          this.checkedItemUpdateModel = this.setFieldsDefaultVal(this.childAddFieldsModel._fieldInfo, updateData)
          this.checkedItemUpdateModel = this.checkedItemUpdateModel.map((item) => {
            if (item.col_type == 'Enum') {
              item['_options'] = item.options.map((opt) => {
                opt['text'] = opt.value
                return opt
              })

            }
            return item
          })

          this.updateColumns = this.checkedItemUpdateModel.filter(item => this.config.popupColumns.includes(item
            .column))

        }

      },
      close() {
        this.$refs.popupUpdate.close()
      },
      scroll(e) {
        // console.log(e)
      },
      buildSections(tabs, type) { // type custom request  
        // generate tab.condition, order, depend_sections from json string to js object/array
        console.log("buildSections", tabs)
        let self = this
        let tab = {}
        let tabsData = []
        if (type && type == 'custom') {
          tabs.forEach((t, index) => {
            tab = {
              service: null,
              table_name: null,
              orders: null,
              conditions: null,
              seq: null,
              parent: null,
              label: null,
              list_tab_no: null,
              more_config: null,
              inputType: null
            }
            tab.service = t.service || ''
            tab._colName = t.colName.split(',') || null
            tab._type = t.type || null
            tab.inputType = t.inputType || null
            tab.colspan = t.colspan
            tab.label = t.label
            tab.placeholder = t.placeholder || t.type === 'Select' ? '请选择' : '请输入'
            tab.showAllTag = t.showAllTag || false
            tab.list_tab_no = t.list_tab_no || 'custom' + index
            tab._data = t
            tab.showLabel = t.showLabel
            tab.appendSearchButton = t.appendSearchButton || false
            tab._options = [] // 选项列表数据
            tab.option_list = t.options || null // 配置
            if (tab._colName) {
              let cols = tab._colName
              let srvCols = self.cols
              tab['_colSrvData'] = []
              // console.log("tab",tab)
              for (let c = 0; c < cols.length; c++) {
                for (let cs = 0; cs < srvCols.length; cs++) {
                  if (cols[c] === srvCols[cs].columns) {
                    tab._colSrvData.push(srvCols[cs])
                  }
                }
              }

            }
            if (tab.inputType == 'tree') {
              tab._options = t.option_list_v2
            }
            if (tab.inputType == 'fk') {
              let cond = [{
                "colName": tab.option_list.key_disp_col,
                "ruleType": "[like]",
                "value": ''
              }]
              cond = cond.concat(tab.option_list ? tab.option_list.conditions : [])
              // cond.push(tab.option_list.conditions)
              console.log("build option ", tab)
              let req = this.selectRequestObjs(tab.option_list.serviceName, cond, null, this
                .relationCondition)
              req.page = {
                rownumber: 100
              }
              let options = []
              this.$fetch('select', tab.option_list.serviceName, req).then((res) => {
                let resData = res.data
                for (let i = 0; i < resData.length; i++) {
                  let item = resData[i]
                  let opt = {
                    value: item[tab.option_list.refed_col],
                    label: item[tab.option_list.key_disp_col],
                    text: item[tab.option_list.key_disp_col]
                  }
                  options.push(opt)

                }

                // self.formModel[e.list_tab_no]['options'] = options
                tab["_options"] = options
                tab["page"] = res.data.page
                // return options
                console.log("options", options)
                //  resolve(options)
              })

            } else if (tab.inputType == 'enum' && tab._colSrvData.length > 0) {
              let colOptions = tab._colSrvData[0].option_list_v2
              tab._options = colOptions.map((item) => {
                let itemVal = {
                  text: item.label,
                  value: item.value
                }
                return itemVal
              })
            }
            tabsData.push(tab)
          })
        } else {
          tabs.forEach((t) => {
            tab = {
              service: null,
              table_name: null,
              orders: null,
              conditions: null,
              seq: null,
              parent: null,
              label: null,
              list_tab_no: null,
              more_config: null,
              inputType: null
            }

            let mc = JSON.parse(t.more_config)
            // console.log("JSON.parse",t.more_config,JSON.parse(t.more_config))
            tab.more_config = JSON.parse(t.more_config)
            tab.service = t.service
            tab.table_name = t.table_name
            tab.conditions = mc.option_list ? mc.option_list.conditions : null || []
            tab.orders = t.orders
            tab.default = mc.default
            tab.seq = t.seq
            tab.label = t.label
            tab.list_tab_no = t.list_tab_no
            tab._data = t
            tab._options = []
            tab._type = mc.type || null
            tab.option_list = JSON.parse(t.more_config).option_list || null
            tab._colName = mc.colName || null
            tab.inputType = mc.inputType || null
            tab.showAllTag = mc.showAllTag || false
            tab.default = mc.default || '',
              tab.placeholder = mc.placeholder || mc.type === 'select' ? '请选择' : '请输入'
            tab.remoteMethod = ""

            if (tab._colName) {
              tab._colName = tab._colName.split(',')
              let cols = tab._colName
              let srvCols = self.cols
              tab['_colSrvData'] = []
              // console.log("tab",tab)
              for (let c = 0; c < cols.length; c++) {
                for (let cs = 0; cs < srvCols.length; cs++) {
                  if (cols[c] === srvCols[cs].columns) {
                    tab._colSrvData.push(srvCols[cs])
                  }
                }
              }

            }
            if (tab.inputType == 'fk') {
              let cond = [{
                "colName": tab.option_list.key_disp_col,
                "ruleType": "[like]",
                "value": ''
              }]
              cond = cond.concat(tab.option_list ? tab.option_list.conditions : [])
              // cond.push(tab.option_list.conditions)
              console.log("build option ", tab)
              let req = this.selectRequestObjs(tab.option_list.serviceName, cond, null, this
                .relationCondition)
              let options = []
              this.$fetch('select', tab.option_list.serviceName, req).then((res) => {
                let resData = res.data.data
                for (let i = 0; i < resData.length; i++) {
                  let item = resData[i]
                  let opt = {
                    value: item[tab.option_list.refed_col],
                    label: item[tab.option_list.key_disp_col]
                  }
                  options.push(opt)

                }

                // self.formModel[e.list_tab_no]['options'] = options
                tab["_options"] = options
                tab["page"] = res.data.page
                // return options
                console.log("options", options)
                //  resolve(options)
              })
            }
            tabsData.push(tab)
          })
        }

        if (tabsData.length > 0 && !self.tabsBuild) {
          self.tabs = tabsData
          self.tabsBuild = true
        }
      },
      onFilterChange(e) {
        let self = this
        // this.onInputValue = e
        if (e && self.$refs.filterTabs) {
          let tabsConds = self.$refs.filterTabs.buildConditions()
          self.relationCondition = tabsConds
        }
      },
      getTableDatas() {
        let self = this
        this.loading = true
        let tabsConds = self.$refs.filterTabs ? self.$refs.filterTabs.buildConditions() : {}
        // this.$set('relationCondition',tabsConds)
        this.relationCondition = tabsConds
        // this.listpage.pageNo = 0
        this.$nextTick(() => {
          this.getListData(1)
        })

        //console.log("tabsConds",tabsConds)
      },
      onpagintion(e) {
        console.log("onpagintion", e)
        this.getListData(e, "pagintion")
      },
      onBatchSelect(e) {
        console.log("onBatchSelect1", e)
        let self = this
        let importData = e
        let datas = []
        let heads = self.gridHeader
        // console.log("onBatchSelect2", heads)
        let defaultData = self.listData
        let addModel = this.childAddFieldsModel ? this.childAddFieldsModel.srv_cols : []
        let listDatasKeys = defaultData.map((item) => item.goods_no)
        // self.listData = datas.map(item => item)
        if (self.config.defaultData == 'batch-select') {
          for (let imp of importData) {
            let data = {
              _trager: 'add',
              _default: self.deepClone(imp)
            }
            for (let h of heads) {
              if ('inventory_type' == h.columns && h.init_expr == 'mainData.inventory_type') {
                // 处理添加数据的 盘点类型
                imp['inventory_type'] = this.activeInventoryType
                data['inventory_type'] = this.activeInventoryType
              }
              if (h.redundant && h.redundant.dependField == 'goods_no') {
                data[h.columns] = imp[h.redundant.refedCol]
              } else if (h.columns !== 'id' && h['in_' + this.editorType] !== 0) {
                data[h.columns] = imp[h.columns]
              }
            }
            // listDatasKeys =listDatasKeys.concat()
            if (listDatasKeys.indexOf(data.goods_no) == -1) {
              datas.push(self.deepClone(data))
            }
          }
          datas = datas.concat(self.listData)
          self.listData = datas
          this.buildListRedundant()
        }
      },
      validInputVal(val, col, data) {
        let res = val
        let labelMap = {
          purchase_price: "进货价",
          warehousing_num: '入库数量',
          issue_num: '出库数量',
          inventory_num: '盘点数量',
          loss_num: "报损数量",
          shipment_price: "出货价",
          min_stock: '最小库存',
          max_stock: "最大库存"
        }

        if (val && ['purchase_price', 'warehousing_num', 'inventory_num', 'loss_num', 'issue_num', 'shipment_price',
            "min_stock", "max_stock"
          ]
          .includes(col)) {
          if (col === 'inventory_num') {
            if (this.activeInventoryType === '累加') {
              if (Number(data.goods_stock) + Number(val) < 0) {
                uni.showToast({
                  title: '累加状态，盘点数量+库存数量不能小于0',
                  icon: 'none',
                  duration: 3000,
                  mask: true
                })
                return 0
              }
              return val
            }
          }
          if (val < 0) {
            // 不能小于0
            res = Math.abs(val)
            if (labelMap[col]) {
              uni.showToast({
                title: `${labelMap[col]}不能小于零!`,
                icon: 'none',
                duration: 3000,
                mask: true
              })
            }
          }
          if (col === 'issue_num' && data?.stock_num && val > data?.stock_num) {
            res = data.stock_num
            uni.showToast({
              title: `${labelMap[col]}不能大于库存数量（${data?.stock_num}）!`,
              icon: 'none',
              duration: 3000,
              mask: true
            })
          }
        }
        if (val && ['inventory_num', 'warehousing_num', 'loss_num', 'issue_num', "min_stock", "max_stock"].includes(
            col) && parseInt(val) !==
          Number(val)) {
          // 入库数量应为>0的整数
          res = parseInt(val)
          if (labelMap[col]) {
            uni.showToast({
              title: `${labelMap[col]}不能为小数!`,
              icon: 'none'
            })
          }
        }

        if (["min_stock", "max_stock"].includes(col)) {
          console.log('"min_stock", "max_stock"');
          if (val !== 0) {
            if (col === 'min_stock') {
              if (val >= data.max_stock && data.max_stock !== 0) {
                res = 0
                uni.showToast({
                  title: `最低库存必须小于最高库存`,
                  icon: 'none'
                })
              }
            } else if (col === 'max_stock') {
              if (val <= data.min_stock) {
                res = Number(data.min_stock) + 1
                uni.showToast({
                  title: `最高库存必须大于最低库存`,
                  icon: 'none'
                })
              }
            }
          }
        }

        return res
      },
      numberChange(val, data, col) {
        val = this.validInputVal(val, col, data)
        if (data) {
          this.formData = data
        }
        this.formItemActive = col
        this.formData[this.formItemActive] = val
        setTimeout(() => {
          this.popupUpdateFormModelIn(this.formItemActive, val)
        }, 20)
      },
      keyUserInValue(val, data, col) {

        if (col) {
          this.formItemActive = col
        }
        if (val) {
          val = Number(val)
        }
        val = this.validInputVal(val, col, data)

        if (data) {
          this.formData = data
        }
        console.log(val, this.formItemActive);
        this.formData[this.formItemActive] = val
        setTimeout(() => {
          this.popupUpdateFormModelIn(col, val)
        }, 20)

      },
      popupUpdateFormModelIn(col, val) {
        // 键盘输入数据更新到 弹窗 form  model 
        let self = this
        let defaultData = self.defaultData
        let mainSrv = this.config.serviceName
        let modelKeys = Object.keys(self.formData) // 所有可编辑的字段

        let heads = this.gridHeader
        switch (mainSrv) {
          case 'srvretail_inventory_add':
          case 'srvretail_inventory_update':
            this.$set(self.formData, col, val)
            for (const head of heads) {
              if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.func) {
                for (const formCol of modelKeys) {
                  if (formCol == head.column) {
                    const data = self.formData
                    const func = head.redundant.func
                    const val = eval("var zz=" + func + "(data); zz")
                    console.log(head.column, data, val, func)
                    this.$set(self.formData, head.column, val)
                  }
                }
              }

            }
            break;
          case 'srvretail_loss_reporting_add':
          case 'srvretail_loss_reporting_update':
            this.$set(self.formData, col, val)
            for (let head of heads) {
              if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.func && head.redundant.func
                .indexOf(col) !== -1) {
                for (let formCol of modelKeys) {
                  if (formCol == head.column) {
                    let data = self.formData
                    let func = head.redundant.func
                    let newFun = new Function('data', 'return ' + func + '(data)')
                    let val = newFun(data).toFixed(2)
                    // let val = eval("var zz=" + func + "(data); zz(data)")
                    console.log(head.column, val, self.formData)
                    this.$set(self.formData, head.column, val)
                  }
                }
              }

            }
            break;
          case 'srvretail_stock_warning_select':
            this.$set(self.formData, col, val)
            for (let head of heads) {
              if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.func && head.redundant.func
                .indexOf(col) !== -1) {
                for (let formCol of modelKeys) {
                  if (formCol == head.column) {
                    let data = self.formData
                    let func = head.redundant.func
                    let newFun = new Function('data', 'return ' + func + '(data)')
                    let val = newFun(data).toFixed(2)
                    console.log(head.column, val, self.formData)
                    this.$set(self.formData, head.column, val)
                  }
                }
              }
            }
            break;
          default:
            this.$set(self.formData, col, val)
            for (let head of heads) {
              if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.func && head.redundant.func
                .indexOf(col) !== -1) {
                console.log(head, col);
                debugger
                for (let formCol of modelKeys) {
                  if (formCol == head.column) {
                    let data = self.formData
                    let func = head.redundant.func
                    let newFun = new Function('data', 'return ' + func + '(data)')
                    let val = newFun(data).toFixed(2)
                    console.log('mainSrv', head.column, val, self.formData, head.redundant)
                    this.$set(self.formData, head.column, val)
                  }
                }
              }
            }
            break;
        }
      },
      listDataSum(col, datas) {
        let colVal = 0
        let list = datas || []
        let colName = col || ""
        list.forEach((item) => {
          colVal = colVal + (item[colName] ? Number(item[colName]) : 0)
        })
        return Number(colVal.toFixed(2))
      },
      actionsClick(type) {
        let btnType = type || ''
        let self = this
        let itemBarcode = self.checkedItem ? self.checkedItem['goods_barcode'] : ""
        let formModel = self.formData
        switch (btnType) {
          case 'submit':
            // 必填校验
            let requireNum = 0;
            let requireColumns = this.updateColumns.filter(item => item.isRequire === true)
            if (requireColumns.length > 0) {
              requireColumns.forEach(column => {
                if (!self.formData[column.column]) {
                  requireNum += 1
                  let title = column?.col_type == 'Enum' ? `请选择${column.label}!` : `${column.label}为必填!`
                  uni.showToast({
                    title,
                    duration: 2000,
                    icon: 'none'
                  })
                }
              })
            }
            if (requireNum > 0) {
              return
            }
            self.listData.forEach((item, index) => {
              if (item['goods_barcode'] == itemBarcode) {
                for (let col in formModel) {
                  item[col] = formModel[col]
                }
                self.$set(self.listData, index, item)
              }
            })
            self.close()
            if (this.submitOnConfirm === true) {
              uni.showModal({
                title: '提示',
                content: '确认提交?',
                success: (res) => {
                  if (res.confirm) {
                    this.submitInStock('submit', true)
                  }
                }
              })
            }
            break;
          case 'delete':
            self.listData = self.listData.filter(item => item['goods_barcode'] !== itemBarcode)
            self.close()
            break;
          default:
            break;
        }
      },
      dialogConfirm(confirm) {
        let type = this.submitAlertDialog || ''
        this.submitInStock(type, confirm)
      },
      selectConfirm(confirm) {
        console.log('activeInventoryType', this.activeInventoryType)
        this.buildListRedundant()
      },
      buildRequestData() {
        let datas = this.listData
        return datas.map((item) => {
          if (item._trager == 'add') {
            item['goods_no'] = item._default["goods_no"]
            delete item._trager
            delete item._default
          }
          return item
        })
      },
      onDelete() {
        let service = this.config.deleteService;
        console.log(service);
        if (service) {
          const url = `/retail/operate/${service}`
          const req = [{
            "serviceName": service,
            "condition": this.condition
          }]
          this.$http.post(url, req).then(res => {
            if (res?.data?.state === 'SUCCESS') {
              uni.showModal({
                title: '提示',
                content: '删除成功!',
                showCancel: false,
                success: (res) => {
                  if (res.confirm) {
                    uni.navigateBack()
                  }
                }
              })

            } else {
              uni.showToast({
                title: res?.data?.resultMessage,
                icon: 'none'
              })
            }
          })
        }
      },
      submitRequest(type) {
        let self = this
        let actionType = type || ''
        let srv = self.defaultData ? "srvretail_warehousing_update" : "srvretail_warehousing_add"
        let req = []
        let keydispcol = self.childServiceBuild ? self.childServiceBuild.foreign_key.keydispcol : ""
        let referencedColumnName = self.childServiceBuild ? self.childServiceBuild.foreign_key
          .referenced_column_name : ""
        let childSrv = this.serviceV2.service_name.replace("select", this.editorType)
        if ((actionType == 'save' || actionType == 'submit') && !self.defaultData && self.inPageType !==
          'batch-update') {
          srv = this.config.serviceName
          req = [{
            "serviceName": this.config.serviceName,
            "condition": [],
            "data": [{
              "child_data_list": [{
                "serviceName": childSrv,
                "condition": [],
                "depend_keys": [{
                  "type": "column",
                  "add_col": keydispcol,
                  "depend_key": referencedColumnName
                }],
                "data": self.buildRequestData()
              }]
            }]
          }]
          if (['srvretail_warehousing_add', 'srvretail_inventory_add', 'srvretail_issue_add',
              'srvretail_loss_reporting_add'
            ].includes(srv)) {
            req[0].data[0]["channel_source"] = "台式消费机"
          }
          switch (srv) {
            case 'srvretail_warehousing_add':
              req[0].data[0]["warehousing_amount"] = self.listDataSum('subtotal_amount', self.listData)
              req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
              req[0].data[0]["warehousing_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ?
                '已提交' : '待提交'
              break;
            case 'srvretail_issue_add':
              req[0].data[0]["issue_amount"] = self.listDataSum('subtotal_amount', self.listData)
              req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
              req[0].data[0]["issue_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ? '已提交' :
                '待提交'
              break;

            case 'srvretail_inventory_add':
              req[0].data[0]["profit_loss_amount"] = self.listDataSum('profit_loss_amount', self.listData)
              req[0].data[0]["inventory_type"] = self.activeInventoryType
              req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
              req[0].data[0]["inventory_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ?
                '已提交' :
                '待提交'
              break;

            case 'srvretail_loss_reporting_add':
              req[0].data[0]["loss_amount"] = self.listDataSum('loss_amount', self.listData)
              req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
              req[0].data[0]["loss_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ? '已提交' :
                '待提交'
              break;
            case 'srvretail_stock_warning_select':
              // if (self.inPageType == 'batch-update') {
              //   // req = self.deepClone(self.batchUpdateDataRun) 
              // }
              break;
            default:
              break;
          }
        } else if (['submit', 'save'].includes(actionType) && self.inPageType !== 'batch-update') {
          srv = this.config.serviceName
          req = [{
            "serviceName": this.config.serviceName,
            "condition": [{
              "colName": "id",
              "ruleType": "eq",
              "value": self.defaultData[0].id
            }],
            "data": [{}]
          }]
          const state = actionType === 'save' ? '待提交' : '已提交'
          const childData = self.buildRequestData()
          if (Array.isArray(childData) && childData.length > 0) {
            req[0].data[0].child_data_list = []
            const keys = ["warehousing_num", "purchase_price", "purchase_amount", "issue_num", "shipment_price",
              "subtotal_amount", 'shipment_amount', "inventory_num", "goods_stock", 'profit_loss_amount',
              'profit_loss_amount', "loss_num", "cost_price", "loss_reason", "cost_amount"
            ]

            childData.forEach(item => {
              const data = {}
              keys.forEach(key => {
                data[key] = item[key]
              })
              const obj = {
                "serviceName": childSrv,
                "condition": [{
                  colName: 'id',
                  ruleType: 'eq',
                  value: item.id
                }],
                "depend_keys": [{
                  "type": "column",
                  "add_col": keydispcol,
                  "depend_key": referencedColumnName
                }],
                "data": [data]
              }
              if (item.id) {
                req[0].data[0].child_data_list.push(obj)
              }
            })
          }
          switch (srv) {
            case 'srvretail_warehousing_update':
              req[0].data[0]["warehousing_state"] = state
              break;
            case 'srvretail_issue_update':
              req[0].data[0]["issue_state"] = state
              break;
            case 'srvretail_inventory_update':
              req[0].data[0]["inventory_state"] = state
              break;
            case 'srvretail_loss_reporting_update':
              req[0].data[0]["loss_state"] = state
              break;
            default:
              break;
          }
        } else if (self.config.serviceName == 'srvretail_stock_warning_select' && self.inPageType ==
          'batch-update') {
          srv = 'srvretail_stock_warning_update'
          req = self.batchUpdateDataRun()
          if (req.length == 0) {
            uni.showToast({
              icon: "none",
              title: '暂无可提交数据'
            })
            return
          }
        }
        uni.showLoading({
          title: '提交中...'
        })
        self.$fetch('operate', srv, req).then((res) => {
          uni.hideLoading()
          if (res.success) {
            self.dialogClose()
            if (self.inPageType !== 'batch-update') {
              uni.navigateBack()
            } else {
              self.getTableDatas()
            }

          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        }).catch(err => {
          uni.hideLoading()
        })
      },
      submitInStock(type, confirm) {
        let self = this
        this.submitAlertDialog = type
        let actionType = type || ''
        this.dialogTitle = ''
        switch (actionType) {
          case 'delete-current':
            if (confirm) {
              this.onDelete()
            } else {
              let titleMap = {
                'srvretail_warehousing_update': '入库单',
                'srvretail_issue_update': "出库单",
                'srvretail_inventory_update': '盘点单',
                'srvretail_loss_reporting_update': '报损单'
              }
              this.dialogTitle = `是否确认删除该${titleMap[this.config.serviceName]||'数据'}`
              self.$refs.alertDialog.open()
            }
            break;
          case 'delete-all':
            self.$refs.alertDialog.open()
            if (confirm) {
              self.listData = self.listData.filter(item => item['goods_barcode'] == "###")
            }
            break;
          case 'save':
            let res1 = this.validData()
            if (res1) {
              self.$refs.alertDialog.open()
              if (confirm) {
                self.submitRequest(actionType)
              }
            }
            break;
          case 'submit':
            let res2 = this.validData()
            if (res2) {
              if (confirm) {
                self.submitRequest(actionType)
              } else {
                self.$refs.alertDialog.open()
              }
            }
            break;
          default:
            break;
        }
        console.log("submitInStock", type, confirm)
      },
      validData() {
        let res = true
        const isValidNum = (e) => {
          return e || e === 0
        }
        if(this.listData.length===0){
          uni.showToast({
            title: '请选择商品',
            icon: 'none'
          })
          return false
        }
        if (this.config.serviceName === 'srvretail_warehousing_add') {
          if (this.listData.some(item => item.warehousing_num <= 0)) {
            uni.showToast({
              title: '入库数量必须大于0',
              icon: 'none'
            })
            return false
          }
          if (this.listData.some(item => item.warehousing_num <= 0)) {
            uni.showToast({
              title: '入库数量必须大于0',
              icon: 'none'
            })
            return false
          }
          let isPass = this.listData.every(item => item.warehousing_num && isValidNum(item
            .purchase_price) && true)
          if (!isPass) {
            uni.showToast({
              title: '请检查入库数量及进货价是否填写完整',
              icon: 'none'
            })
            return false
          }
        }
        if (this.config.serviceName === 'srvretail_inventory_add') {
          if (this.listData.some(item => item.inventory_num && item.inventory_num && Number(item.inventory_num) !==
              parseInt(item
                .inventory_num))) {
            uni.showToast({
              title: '盘点数量不能为小数',
              icon: 'none'
            })
            return false
          }
          if (this.activeInventoryType === '覆盖') {
            let tips = ''
            if (this.listData.some(item => item.inventory_num < 0)) {
              tips = '类型为覆盖时盘点数量必须大于等于0'
            }
            if (this.listData.some(item => Number(item.inventory_num) !== parseInt(item.inventory_num))) {
              tips = '类型为覆盖时盘点数量必须为>=0的整数'
            }
            if (tips) {
              uni.showToast({
                title: tips,
                icon: 'none'
              })
              return false
            }

          } else if (this.activeInventoryType === '累加' && this.listData.some(item => item.inventory_num + item
              .goods_stock < 0)) {
            uni.showToast({
              title: '类型为累加时盘点数量+系统库存不能小于0',
              icon: 'none'
            })
            return false
          }
          let isPass = this.listData.every(item => (item.inventory_num || item.inventory_num === 0) && true)
          if (!isPass) {
            uni.showToast({
              title: '请检查盘点数量是否填写完整',
              icon: 'none'
            })
            return false
          }
        }
        if (this.config.serviceName === 'srvretail_issue_add') {
          if (this.listData.some(item => item.issue_num <= 0)) {
            uni.showToast({
              title: '出库数量必须大于0',
              icon: 'none'
            })
            return false
          }
          let isPass = this.listData.every(item => item.issue_num && isValidNum(item.shipment_price) &&
            true)
          if (!isPass) {
            uni.showToast({
              title: '请检查出库数量及出货价是否填写完整',
              icon: 'none'
            })
            return false
          }
        }
        if (this.config.serviceName === 'srvretail_loss_reporting_add') {
          if (this.listData.some(item => item.loss_num <= 0)) {
            uni.showToast({
              title: '数量必须大于0',
              icon: 'none'
            })
            return false
          }
          let isPass = this.listData.every(item => item.loss_num && item.loss_reason && true)
          if (!isPass) {
            uni.showToast({
              title: '请检查数量及原因是否填写完整',
              icon: 'none'
            })
            return false
          }
        }
        return res
      },
      dialogClose() {
        let self = this
        self.$refs.alertDialog.close()
        self.submitAlertDialog = ""
      },
      buildListRedundant(newVal) {
        let list = this.listData
        let fields = this.gridHeader
        if (this.config.serviceName == 'srvretail_inventory_add') {
          for (let i = 0; i < list.length; i++) {
            list[i]['inventory_type'] = this.activeInventoryType
            this.$set(this.listData, i, list[i])
          }
        }
        for (let head of fields) {
          if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.hasOwnProperty('func')) {
            for (let item of list) {
              let data = item
              let func = head.redundant.func
              let val = eval("var zz=" + func + "(data, this); zz")
              item[head.column] = val
              this.$set(item, head.column, val)
            }
          }
        }
      }
    },
    watch: {
      "activeInventoryType": {
        handler: function(newVal, oldVal) {
          if ((newVal !== oldVal) && this.config.serviceName == 'srvretail_inventory_add') {
            // this.buildListRedundant(newVal)
          }
        }
      }
    }
  }
</script>

<style scoped>
  .over-css /deep/ .cu-form-group {

    min-height: unset !important;
    position: relative !important;
  }

  .over-css /deep/ .cu-form-group {

    min-height: unset !important;
    position: relative !important;
  }

  .over-css /deep/ .cuIcon-search {
    position: absolute;
    right: 0px;
    display: none;
  }

  .over-css /deep/ .cu-form-group {

    min-height: unset !important;
    position: relative !important;
  }



  .over-css /deep/ .text-lg {
    font-size: 18px !important;
  }

  .over-css /deep/ .tree-node {
    font-weight: 300 !important;
  }



  .over-css /deep/ .form-item-button {

    /* min-width: unset !important; */
    max-width: unset !important;
    width: unset !important;
  }

  .over-css /deep/ .cu-form-group {


    width: unset !important;
  }
</style>
<style lang="scss" scoped>
  $bottom-button-height:8rem;
  $bottom-button-font-size:2rem;
  $middle-body-height:calc(100vh - 16rem);
  $padding:0.5rem 1rem;



  .card-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .card-actions-item {
      font-size: 3rem;
      padding: 2rem 3rem;
      line-height: 4rem;
      margin-left: 2rem;
      margin-right: 0;
    }

  }

  .retail-list {
    width: 100%;
    // background-color: $retail-color-primary;
    display: flex;
    height: calc(100vh - 16rem);
    flex-direction: row;
    justify-content: space-between;

    .retail-list-block {
      width: 100%;

      .retail-list-left-middle {
        min-height: 90upx !important;

      }
    }

    .retail-list-left {
      padding: 0upx;
      height: 100%;
      width: calc(100vw - 70%);

      .retail-list-left-middle {
        .scroll-left {
          height: calc(100vh - 16rem);
        }

        &,
        .full-height {
          height: 100%;
        }
      }
    }

    .retail-list-left,
    .retail-list-block {
      // padding: 20upx;
      background-color: #f2f2f2;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .retail-list-left-middle {
        overflow-y: auto;

        .list-item-inline {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        }
      }

      .retail-list-left-top {

        // height: $bottom-button-height;
        .cu-btn.lg {
          height: $bottom-button-height;
          font-size: $bottom-button-font-size;
        }
      }

      .retail-list-left-bottom {

        // height: $bottom-button-height;
        .cu-btn.lg {
          height: $bottom-button-height;
          font-size: $bottom-button-font-size;
        }
      }
    }

    .retail-list-right.retail-list-right-full {
      width: calc(100vw - 30%);
    }

    .retail-list-right {
      padding: $padding;
      width: calc(100vw - 0%);
      background-color: #f2f2f2;
      display: flex;
      flex-direction: column;
      // height: calc(100vh - 270rpx);
      justify-content: space-between;

      .retail-list-right-top {
        height: 12rem;
        display: flex;
        flex-direction: row;
        align-items: center;

        .margin-right {
          // margin-right: 10rem;
        }
      }

      .retail-list-right-middle {
        height: 100%;
        position: relative;
        display: flex;
        flex-direction: column;

        .loading-box {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          min-height: 50rem;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 999;
          background-color: rgba(255, 255, 255, 0.7);
        }

        ::v-deep .r-paging {
          width: 100%;

          .bx-pagination {
            width: 100%;
          }

          .uni-pagination {
            justify-content: flex-end;
            // position: absolute;
            // right: 0;
            // bottom: 0;
            background-color: #fff;
            z-index: 999;
            width: 100%;
            padding: 1rem;
          }
        }

        ::v-deep .uni-table-scroll {
          // min-height: 100%;
          // height: 100%;
          flex: 1;

          .table {
            padding-bottom: 20rem;

          }

          .uni-table {
            overflow-y: scroll;
            padding-bottom: 20rem;
            // padding-top: 7.5rem;
            // position: relative;
            // .fixed-head{
            //   position: absolute;
            //   top: 0;
            //   width: 100%;
            //   left: 0;
            //   right: 0;
            // }

          }
        }

        .list-item-inline {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        }

        overflow-y: auto;
      }

      .retail-list-right-bottom {
        // height: $bottom-button-height;
        display: flex;
        justify-content: space-between;
        flex-direction: row;

        .buttom-layout {
          display: flex;
          flex-direction: row;

          .count-layout {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            text-align: center;
            font-size: 2.4rem;
            // height: 14rem;
            border-right: 2px solid #f2f2f2;

            * {
              min-width: 100%;
            }

            &:last-child {
              border-right: 0;
            }
          }
        }

        .buttom-buttons {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
          align-items: center;

          .batch-submit {
            // height: 12rem;
            // line-height: 12rem;
            align-items: center;
            font-size: 3rem;
            background-color: $retail-color-light;
            margin-right: 20rpx !important;
          }

          .bg-red {
            background-color: #dd524d;
            color: #fff;
          }

          uni-button {
            // height: 12rem;
            // line-height: 12rem;
            // align-items: center;
            font-size: 3rem;
            margin-right: 1rem;
            min-width: 16rem;
          }

          uni-button[disabled]:not([type]),
          [type=default] {
            background-color: $retail-color-primary;
            color: #fff;
          }

          uni-button[type=info] {
            color: #000;
            background-color: $uni-bg-color-grey;
          }

          uni-button[disabled]:not([type]),
          [type=primary] {
            background-color: $retail-color-primary;
            color: #fff;

          }

          uni-button[type=error] {
            color: #fff;
            background-color: $uni-color-error;
          }
        }
      }
    }

    .uni-list {
      background-color: #f2f2f2;

      .uni-list-item {
        padding: 20upx;
        margin-bottom: 10upx !important;
      }
    }
  }

  .item-update {
    .uni-input {
      border-radius: 1rem;
      border: 1px solid #e5e5e5;
      height: 6.8rem;
      line-height: 6.8rem;
      padding: 0 1rem;
      font-size: 2.4rem;

      &[disabled] {
        background-color: #F8F8F8;
        pointer-events: none;
      }
    }

    // .uni-input[disabled] {
    //   background-color: #F8F8F8;
    //   pointer-events: none;
    // }

    ::v-deep .uni-input.active {
      border-color: #38C09E;
      background-color: #fff;
    }
  }

  ::v-deep .uni-input-wrapper {
    font-size: 2.4rem;
  }
</style>
